<template>
  <div class="allBox">
    <div class="addBox">
      <dt-info :label-width="120" ref="proInfo"></dt-info>
      <Tabs v-model="permissionVal" type="card">
        <TabPane label="期内套餐" name="1">
          <div class="permissionCon">
            <div class="permissionBox" v-for="item in editInfo.duringPackage" :key="item.id">
              <Checkbox v-model="item.checked" class="checkCon"></Checkbox>
              <div class="permiss">
                <p class="p1">
                  {{ item.title }}
                  <span @click="searchPermission(item)">查看权限</span>
                </p>
                <p class="p2">
                  {{ item.internalContent }}
                </p>
              </div>
            </div>
          </div>
        </TabPane>
        <TabPane label="期外套餐" name="2">
          <div class="permissionCon">
            <div class="permissionBox" v-for="item in editInfo.extraPackage" :key="item.id">
              <Checkbox v-model="item.checked" class="checkCon"></Checkbox>
              <div class="permiss">
                <p class="p1">
                  {{ item.title }}
                  <span @click="searchPermission(item)">查看权限</span>
                </p>
                <p class="p2">
                  {{ item.internalContent }}
                </p>
              </div>
            </div>
          </div>
        </TabPane>
      </Tabs>
      <dt-info :label-width="120" ref="proInfo2"></dt-info>
      <div class="boxAll">
        <div class="btnBox flex flex-horizontal-between">
          <Button @click="cancel">取消</Button>
          <Button type="success" @click="temporary">暂存</Button>
          <Button type="primary" @click="proConfirm">项目确认</Button>
        </div>
      </div>
    </div>

    <Modal v-model="showModal" title="验证手机号" width="30%" @on-ok="checkOk" class="audio-modal">
      <p>
        该手机号为已注册手机号， 注册人员：{{ userPhoneVal.userName }}({{ userPhoneVal.workNumber }})。
        <br />
        <span style="color: #2d8cf0; cursor: pointer" @click="zpeople">查看人员所属组织</span>
        请确认，是否以该人员作为项目归属人？
      </p>
    </Modal>

    <Modal v-model="leaveModal" title="离开" :footer-hide="true" transfer>
      <p class="leaveP1">您即将离开当前页面，请确认是否对已编辑的内容进行保存？</p>
      <div class="leaveBtnBox">
        <Button @click="noSave">不保存</Button>
        <Button type="primary" @click="temporary">保存</Button>
      </div>
    </Modal>
    <permission-tree ref="permissionTreeRef"></permission-tree>
    <pro-sure ref="proSureRef"></pro-sure>
    <belong-user-org ref="belongUserOrgRef"></belong-user-org>
  </div>
</template>

<script setup>
  import { watch, onMounted, onBeforeMount, reactive, ref, nextTick } from 'vue'
  import { useRouter } from 'vue-router'
  import proSure from '../components/proSure.vue'
  import belongUserOrg from '../components/belongUserOrg.vue'
  import { editOpt, refuelingOpt } from './biz/edit'
  import apiMgr from '../biz/index.js'
  import permissionTree from '../components/permissionTree'
  import router from '@/router'
  import dt from '@dt/dt'
  const [proInfo, proInfo2, permissionVal, permissionTreeRef, proSureRef, belongUserOrgRef] = [
    ref(),
    ref(),
    ref('1'),
    ref(false),
    ref(),
    ref()
  ]
  const proId = ref()
  const editInfo = ref({
    tenantName: '',
    companyId: '',
    companyName: '',
    belongUserPhone: null,
    phoneVerify: null,
    belongUserName: '',
    city: [],
    peopleCity: [],
    cityName: '',
    cityCode: '',
    provinceCode: '',
    effectEndDate: null,
    effectStartDate: null,
    day: '',
    accountNumber: '',
    remark: '',
    duringPackage: [], //期内
    duringPackageIds: [],
    extraPackage: [], //期外
    extraPackageIds: [],
    cityCode: '',
    provinceCode: ''
  })
  const showModal = ref(false)
  const leaveModal = ref(false)
  onBeforeMount(() => {
    getPackages()
  })
  onMounted(() => {
    proId.value = useRouter().currentRoute.value.query.id
    if (proId.value) {
      proDetailsById()
    } else {
      proInfo.value.init(new editOpt(fun), editInfo.value)
      proInfo2.value.init(new refuelingOpt(fun), editInfo.value)
    }
  })

  const proDetailsById = async () => {
    const params = {
      tenantId: proId.value
    }
    try {
      const res = await apiMgr.tenantDetailsForWeb(params)
      console.log(res, '11222')
      editInfo.value.tenantName = res.tenantName
      editInfo.value.companyId = res.companyId
      editInfo.value.companyName = res.companyName
      editInfo.value.provinceCode = res.provinceCode
      editInfo.value.cityCode = res.cityCode
      editInfo.value.belongUserName = res.belongUserName
      editInfo.value.belongUserPhone = res.belongUserPhone
      editInfo.value.phoneVerify = res.belongUserPhone
      editInfo.value.remark = res.remark
      editInfo.value.effectStartDate = res.effectStartDate
      editInfo.value.effectEndDate = res.effectEndDate
      editInfo.value.day = res.effectDay
      editInfo.value.accountNumber = String(res.accountNumber)
      editInfo.value.duringPackageIds = res.duringPackageIds
      editInfo.value.extraPackageIds = res.extraPackageIds
      editInfo.value.peopleCity = [res.provinceCode, res.cityCode]
      editInfo.value.city = [res.provinceName, res.cityName]
      console.log(editInfo.value, 'editInfo.value.duringPackage')
      editInfo.value.duringPackage.forEach((item) => {
        item.checked = editInfo.value.duringPackageIds.includes(item.id)
      })
      editInfo.value.extraPackage.forEach((item) => {
        item.checked = editInfo.value.extraPackageIds.includes(item.id)
      })
      proInfo.value.init(new editOpt(fun), editInfo.value)
      proInfo2.value.init(new refuelingOpt(fun), editInfo.value)
    } catch (error) {
      console.log(error)
    }
  }
  const getPackages = () => {
    apiMgr.getPackages().then((res) => {
      res.forEach((item) => {
        item.checked = false
      })
      editInfo.value.duringPackage = dt.tool.deepClone(res)
      editInfo.value.extraPackage = dt.tool.deepClone(res)
    })
  }
  async function proConfirm() {
    try {
      const res1 = await proInfo.value.validate()
      const res2 = await proInfo2.value.validate()
      console.log(res1, res2, 'vvv11')
      let duFlag = editInfo.value.duringPackage.some((item) => item.checked)
      let exFlag = editInfo.value.extraPackage.some((item) => item.checked)
      if (res1 && res2) {
        if (!duFlag) {
          dt.ui.Message.warning('请至少选择一个期内套餐')
          return false
        }
        if (!exFlag) {
          dt.ui.Message.warning('请至少选择一个期外套餐')
          return false
        }

        console.log(editInfo.value, 'editInfo.value')
        proSureRef.value.show(editInfo.value)
      }
    } catch (error) {
      // 处理错误
    }
  }
  function temporary() {
    editInfo.value.duringPackageIds = editInfo.value.duringPackage
      .filter((item) => item.checked)
      .map((item) => item.id)
    editInfo.value.extraPackageIds = editInfo.value.extraPackage
      .filter((item) => item.checked)
      .map((item) => item.id)
    if (!editInfo.value.tenantName) {
      dt.ui.Message.warning('请填写项目名称')
      return false
    }
    let params = {
      accountNumber: editInfo.value.accountNumber,
      belongUserName: editInfo.value.belongUserName,
      belongUserPhone: editInfo.value.belongUserPhone,
      cityCode: editInfo.value.peopleCity[1],
      companyId: editInfo.value.companyId,
      duringPackageIds: editInfo.value.duringPackageIds,
      effectEndDate: editInfo.value.effectEndDate,
      effectStartDate: editInfo.value.effectStartDate,
      extraPackageIds: editInfo.value.extraPackageIds,
      provinceCode: editInfo.value.peopleCity[0],
      remark: editInfo.value.remark,
      tenantName: editInfo.value.tenantName,
      tenantStatus: 1
    }
    apiMgr.saveTenantForWeb(params).then((res) => {
      dt.ui.Message.success('暂存成功')
      leaveModal.value = false
      if (res == 2) {
        router.push({
          path: '/tenant/package/project/list'
        })
      }
    })
  }
  function searchPermission(val) {
    console.log(val, 'ddddd')
    permissionTreeRef.value.show(val.id, val.title)
  }

  const userPhoneVal = ref({})
  function zpeople() {
    belongUserOrgRef.value.show(userPhoneVal.value)
  }
  function checkOk() {
    editInfo.value.phoneVerify = userPhoneVal.value.phone
    editInfo.value.belongUserName = userPhoneVal.value.userName
  }
  const cancel = () => {
    leaveModal.value = true
  }
  const noSave = () => {
    leaveModal.value = false
    router.push({
      path: '/tenant/package/project/list'
    })
  }
  const fun = {
    onShowCheckCity: () => {
      console.log(editInfo.value.city, 'editInfo.value.city')
      return editInfo.value.city.join('/')
    },
    checkPhone: () => {
      console.log(editInfo.value, editInfo.value.belongUserPhone, 'editInfo.value.belongUserPhone')
      let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (!reg.test(editInfo.value.belongUserPhone)) {
        return dt.ui.Message.warning('请输入正确的手机号')
      } else {
        let params = {
          phone: editInfo.value.belongUserPhone
        }
        apiMgr.getTenantInfoByPhoneForWeb(params).then((res) => {
          userPhoneVal.value = res
          console.log(res, 'res')
          if (!res.registerStatus) {
            dt.ui.Modal.confirm({
              title: '验证手机号',
              content: `该手机号为未注册手机号。<br/>请确认，是否以该手机号作为归属人手机号并创建新用户?`,
              onOk: () => {
                editInfo.value.phoneVerify = editInfo.value.belongUserPhone
              },
              onCancel: () => {
                dt.ui.Message.info('您取消了操作。')
              }
            })
          } else {
            showModal.value = true
          }
        })
      }
    },
    chooseCompanyName: (val) => {
      editInfo.value.companyName = val.label
    },
    chooseCity: (val) => {
      if (val && val.length) {
        editInfo.value.cityName = `${val[0].cityName}-${val[1].cityName}`
        console.log(editInfo.value.cityName, editInfo.value.peopleCity, '城市')
      }
    },
    dataChange: (val) => {
      if (editInfo.value.effectEndDate && editInfo.value.effectStartDate) {
        let flag =
          new Date(editInfo.value.effectEndDate).getTime() <
          new Date(editInfo.value.effectStartDate).getTime()
        if (flag) {
          nextTick(() => {
            editInfo.value.effectEndDate = ''
            dt.ui.Message.warning('结束时间不能小于开始时间')
          })
        }
        const timeDiff = Math.abs(
          new Date(editInfo.value.effectEndDate).getTime() -
            new Date(editInfo.value.effectStartDate).getTime()
        )
        editInfo.value.day = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)) + 1
      }
    }
  }
</script>
<style scoped lang="scss">
  .allBox {
    height: calc(100% - 30px);
    overflow-y: auto;
    overflow-x: hidden;

    .addBox {
      width: 80%;
      padding-bottom: 40px;
      .title {
        position: relative;
        padding-left: 16px;
        margin: 10px 0;
      }
      .title::before {
        content: '';
        width: 8px;
        height: 16px;
        background: #2d61f4;
        position: absolute;
        left: 0;
        top: 4px;
      }
      .permissionCon {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        flex-wrap: wrap; /* 设置换行 */
        .permissionBox {
          border: 1px #eee solid;
          width: 49%;
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          padding: 20px;
          margin-bottom: 10px;
          .checkCon {
            width: 20px;
          }
          .permiss {
            flex: 1;
            .p1 {
              font-size: 14px;
              font-weight: bold;
              span {
                font-weight: normal;
                color: #2d61f4;
                cursor: pointer;
              }
            }
            .p2 {
              line-height: 2;
              margin-top: 10px;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2; /* 设置最大行数为2 */
              overflow: hidden;
              text-overflow: ellipsis; /* 文本超出显示省略号 */
            }
          }
        }
      }
    }
    .boxAll {
      position: fixed;
      bottom: 0px;
      left: 0;
      width: 100%;
      margin-left: 200px;
    }
    .btnBox {
      width: 300px;
      padding: 20px 0;
      background: #fff;
      margin: 0 auto;
    }
  }
  .leaveP1 {
    text-align: center;
    margin: 20px 0;
  }
  .leaveBtnBox {
    width: 200px;
    margin: 0 auto;
    padding: 20px 0;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
  }
</style>
